package com.example.ktapplication.model
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.bean.HomeArticleBean
import com.example.ktapplication.bean.HomeBannerBean
import com.example.ktapplication.state.ArticleState
import com.example.ktapplication.state.HomeBannerState
import com.example.ktapplication.utils.NetworkUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import com.example.ktapplication.net.NetRepository

class ArticleViewModel: ViewModel() {
    private val _state = MutableStateFlow<ArticleState>(ArticleState.OnSuccess(null))
    val state: StateFlow<ArticleState> = _state
    var page:Int=0;
    fun getHomeAritcleData(size:Int) {
        page=size
        viewModelScope.launch {
            aritcle.flowOn(Dispatchers.IO)
                .catch { exception ->
                    _state.value = ArticleState.OnError(exception)
                }
                .collect { data ->
                    _state.value = ArticleState.OnSuccess(data)
                }
        }
    }

    private val aritcle: Flow<HomeArticleBean> = flow {
        if (!NetworkUtils.isConnected(AppGlobals.getApplication())){
            throw RuntimeException("网络未连接")
        }
        //网络请求
        val aritcle = NetRepository.instance.service.getArticleList(page)
        //返回结果
        emit(aritcle)
    }

    override fun onCleared() {
        super.onCleared()
    }
}